const jwt = require('jwt-simple')
const serverName = '微信管理'
const tokenSecret = '*8^Juse@2018sRtH0icD2gTfwer%#'
module.exports = function (req, res, next) {
  if (!req.header('Authorization')) {
    return res.status(401).send({ message: '无请求头' })
  }
  const token = req.header('Authorization').split(' ')[1]
  let payload
  try {
    payload = jwt.decode(token, tokenSecret)
  }
  catch (err) {
    return res.status(401).send({ message: '无权限' })
  }
  req.user = payload
  if (payload.root) {
    return next()
  }
  if (!payload.departmentNumber || !payload.rolesNumber || !payload.authNumber) {
    return res.status(401).send({ message: '无权限' })
  }
  if (Object.prototype.toString.call(payload.rolesNumber) !== '[object Array]') {
    return res.status(401).send({ message: '无权限' })
  }
  if (Object.prototype.toString.call(payload.authNumber) !== '[object Array]') {
    return res.status(401).send({ message: '无权限' })
  }
  const auth = payload.auth[serverName]
  // if (!auth || !auth[req.baseUrl + req.path]) {
  //   return res.status(401).send({ message: '无权限' })
  // }
  next()
}